package fcy.ui;

import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.*;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarLineChartBase;
import com.github.mikephil.charting.charts.Chart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.filter.Approximator;
import com.github.mikephil.charting.data.filter.Approximator.ApproximatorType;
import com.github.mikephil.charting.formatter.FillFormatter;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.utils.Utils;
import com.xxmassdeveloper.mpchartexample.R;
import com.xxmassdeveloper.mpchartexample.model.MarkerInfo;
import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase;
import com.xxmassdeveloper.mpchartexample.util.RawUtils;
import fcy.TopMarkerView;

import java.util.ArrayList;
import java.util.List;

public class MyLineChartActivity extends DemoBase {

	private LineChart mChart;
	// 线条等颜色
	private int COLOR;
	private List<MarkerInfo> markeInfos;
	/**
	 * 存放数据:先initLineData,然后setData,然后resetAnim
	 */
	private LineData mLineData;
	private int TIME_ANIM = 1500;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_my_linechart);
		COLOR = getResources().getColor(R.color.green_lianjia);

		markeInfos = JSON.parseArray(RawUtils.getJsonString(this, R.raw.data), MarkerInfo.class);

		mChart = (LineChart) findViewById(R.id.chart1);
		mChart.disableAll();

		// 设置setOnlyMarkClickListener中设置了setOnTouchListener会覆盖掉BarLineChartBase中的touchListener
		// ，从而所有的drag,scale及各种手势处理也就无效了也就无效了
		mChart.setOnlyMarkClickListener(new BarLineChartBase.OnMarkClickListener() {
			@Override
			public void clickMark(int position, Entry entry) {
				MarkerInfo markerInfo = (MarkerInfo) entry.getData();
				Toast.makeText(MyLineChartActivity.this, markerInfo.district_name + entry.toString(), Toast
					.LENGTH_SHORT)
					.show();
			}
		});
		//mChart.setTouchEnabled(true);
		//mChart.setDragEnabled(false);
		//mChart.setScaleEnabled(false);
		// mChart.setScaleXEnabled(true);
		// mChart.setScaleYEnabled(true);

		mChart.setMarkerView(new TopMarkerView(this, R.layout.top_marker_view));
		// 设置最大刻度值为12
		mChart.getAxisLeft().setAxisMaxValue(13);
		// 围绕中心点缩放就不需要再移动了
		// fixme 默认显示全部5个点，现在需要显示3个半的，就需要放大
		mChart.zoom(4 / 3.3f, 1, 0, 0);
		//  绘制数据
		drawData(markeInfos);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.line, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
			case R.id.actionToggleValues: {
				List<ILineDataSet> sets = mChart.getData().getDataSets();

				for (ILineDataSet iSet : sets) {

					LineDataSet set = (LineDataSet) iSet;
					set.setDrawValues(!set.isDrawValuesEnabled());
				}

				mChart.invalidate();
				break;
			}
			case R.id.actionToggleHighlight: {
				if (mChart.getData() != null) {
					mChart.getData().setHighlightEnabled(!mChart.getData().isHighlightEnabled());
					mChart.invalidate();
				}
				break;
			}
			case R.id.actionToggleFilled: {

				List<ILineDataSet> sets = mChart.getData().getDataSets();

				for (ILineDataSet iSet : sets) {

					LineDataSet set = (LineDataSet) iSet;
					if (set.isDrawFilledEnabled()) {
						set.setDrawFilled(false);
					} else {
						set.setDrawFilled(true);
					}
				}
				mChart.invalidate();
				break;
			}
			case R.id.actionToggleCircles: {
				List<ILineDataSet> sets = mChart.getData().getDataSets();

				for (ILineDataSet iSet : sets) {

					LineDataSet set = (LineDataSet) iSet;
					if (set.isDrawCirclesEnabled()) {
						set.setDrawCircles(false);
					} else {
						set.setDrawCircles(true);
					}
				}
				mChart.invalidate();
				break;
			}
			case R.id.actionToggleCubic: {
				List<ILineDataSet> sets = mChart.getData().getDataSets();

				for (ILineDataSet iSet : sets) {

					LineDataSet set = (LineDataSet) iSet;
					if (set.isDrawCubicEnabled()) {
						set.setDrawCubic(false);
					} else {
						set.setDrawCubic(true);
					}
				}
				mChart.invalidate();
				break;
			}
			//case R.id.actionToggleStartzero: {
			//	mChart.getAxisLeft().setStartAtZero(!mChart.getAxisLeft().isStartAtZeroEnabled());
			//	mChart.getAxisRight().setStartAtZero(!mChart.getAxisRight().isStartAtZeroEnabled());
			//	mChart.invalidate();
			//	break;
			//}
			case R.id.actionTogglePinch: {
				if (mChart.isPinchZoomEnabled()) {
					mChart.setPinchZoom(false);
				} else {
					mChart.setPinchZoom(true);
				}

				mChart.invalidate();
				break;
			}
			case R.id.actionToggleAutoScaleMinMax: {
				mChart.setAutoScaleMinMaxEnabled(!mChart.isAutoScaleMinMaxEnabled());
				mChart.notifyDataSetChanged();
				break;
			}
			case R.id.animateX: {
				//mChart.animateX(3000);
				//setData();
				resetAnim();
				break;
			}
			case R.id.animateY: {
				mChart.animateY(TIME_ANIM, Easing.EasingOption.EaseInCubic);
				break;
			}
			case R.id.animateXY: {
				mChart.animateXY(TIME_ANIM, TIME_ANIM);
				break;
			}
			//case R.id.actionToggleFilter: {
            //
			//	// the angle of filtering is 35°
			//	Approximator a = new Approximator(ApproximatorType.DOUGLAS_PEUCKER, 35);
            //
			//	if (!mChart.isFilteringEnabled()) {
			//		mChart.enableFiltering(a);
			//	} else {
			//		mChart.disableFiltering();
			//	}
			//	mChart.invalidate();
			//	break;
			//}
			case R.id.actionSave: {
				if (mChart.saveToPath("title" + System.currentTimeMillis(), "")) {
					Toast.makeText(getApplicationContext(), "Saving SUCCESSFUL!", Toast.LENGTH_SHORT)
						.show();
				} else {
					Toast.makeText(getApplicationContext(), "Saving FAILED!", Toast.LENGTH_SHORT)
						.show();
				}

				// mChart.saveToGallery("title"+System.currentTimeMillis())
				break;
			}
		}
		return true;
	}

	/**
	 * 设置线条UI
	 *
	 * @param line
	 */
	private void setLineUI(@NonNull LineDataSet line) {
		// 不绘制yVals
		line.setDrawValues(false);
		// 设置连接线为虚线
		//set1.enableDashedLine(10f, 5f, 0f);
		// 设置高亮线为虚线
		//set1.enableDashedHighlightLine(10f, 5f, 0f);
		// 设置节点连线的颜色
		line.setColor(COLOR);

		// 改变折线样式，用曲线，默认false用直线
		// set1.setDrawCubic(true);
		// 曲线的平滑度，值越大越平滑。
		// set1.setCubicIntensity(0.2f);
		// 节点线宽 dp
		line.setLineWidth(1f);

		// 显示的节点圆圈大小
		line.setOutCircleStrokeColor(getResources().getColor(R.color.blue));
		line.setCircleRadius(8f);
		// 节点圆圈的颜色
		line.setCircleColor(Color.WHITE);
		line.setDrawCircleStroke(true);
		// 允许圆圈中间有洞
		line.setDrawCircleHole(true);
		line.setCircleHoleRadius(4);
		// 填充折线上数据点、圆球里面包裹的中心空白处的颜色。
		line.setCircleColorHole(COLOR);
		//set1.setValueTextSize(9f);
		line.setFillAlpha(80);
		// 连线封闭区域颜色
		//set1.setFillColor(Color.BLUE);

		// 填充曲线下方的区域，红色，半透明。
		line.setDrawFilled(false);
		// 由于表格在ScrollView中必须给出高度，所以这里可以写死高度，mChart.getHeight()这里拿不到
		line.setShader(new LinearGradient(0, 0, 0, Utils.convertDpToPixel(185), Color.parseColor("#7af5c3"), Color.WHITE, Shader.TileMode.MIRROR));
		// // Highlight的十字交叉的横线将不会显示，
		//set1.setDrawHorizontalHighlightIndicator(false);
		// Highlight的十字交叉的纵横线将不会显示，
		line.setDrawHighlightIndicators(false);
		// 按击后，十字交叉线的颜色
		//set1.setHighLightColor(Color.CYAN);

		// 设置这项上显示的数据点的字体大小。
		//set1.setValueTextSize(10.0f);
		// TODO formatter绘制渐变最低值
		line.setFillFormatter(new FillFormatter() {
			@Override
			public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
				return 3;
			}
		});
	}

	/**
	 * 初始化数据
	 */
	private void initLineData(List<MarkerInfo> markeInfos) {
		// 1.初始化每个节点数据
		ArrayList<String> xVals = new ArrayList<String>();
		ArrayList<Entry> yVals = new ArrayList<Entry>();
		// 水平只是标度值对应的value，内容没有数值的意义
		for (int i = 0; i < markeInfos.size(); i++) {
			xVals.add(String.valueOf(i));
			yVals.add(new Entry(markeInfos.get(i).height, i, markeInfos.get(i)));
		}
		LineDataSet set1 = new LineDataSet(yVals, "dataset1");
		setLineUI(set1);

		ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
		dataSets.add(set1); // add the datasets

		// create a data object with the datasets
		mLineData = new LineData(xVals, dataSets);
	}

	private void resetAnim() {
		if (mLineData == null || mLineData.getDataSets() == null ||
			mLineData.getDataSets().size() == 0) {
			return;
		}
		// 清除全部高亮以及闭合填充
		mChart.highlightValues(null);
		mLineData.getDataSets().get(0).setDrawFilled(false);
		// 这个动画会保留之前的所有状态从左到有一次显示
		mChart.animateXY(TIME_ANIM, TIME_ANIM);
		//mChart.animateX(TIME_ANIM, Easing.EasingOption.EaseInOutQuart);
		//mChart.animateX(TIME_ANIM);

		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				// 动画结束后再设置填充以及绘制markview
				mLineData.getDataSets().get(0).setDrawFilled(true);
				mChart.highlightPartValues(1,3);
				//mChart.highlightAllValues();
			}
		}, TIME_ANIM);
	}

	private void setData() {
		// set data，填充数据
		mChart.setData(mLineData);
		// 移动几个段（两个节点间距离）的位置，如果放大要根据放大比例（可以在填充数据后再放大，就不用移动了，不过只能放大一次）
		// fixme 放到后，移动到居中位置
		mChart.moveViewToX(2 - 3.3f / 2);
	}

	/**
	 * 绘制数据
	 *
	 * @param markeInfos
	 */
	private void drawData(List<MarkerInfo> markeInfos) {
		initLineData(markeInfos);
		setData();
		//resetAnim();
	}

}
